# from django.shortcuts import render

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import json
import requests
import time
from bs4 import BeautifulSoup
import time
import re
import urllib


#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):
    allData = []
    # 获取sid并且更新返回
    soup = BeautifulSoup(response.text, "html5lib")

    # allNum = soup.find_all('h1',id="number-of-search-results-and-search-terms")[0].find_all('strong')[0].text.replace(',','')

    lis = response.json()["data"]["books"]

    for li in lis:
        tempData = resultData()
        try:
            tempData["titleName"] = li["resourceName"]
        except:
            pass


        try:
            tempData["titleHref"] = "http://zq.bookan.com.cn/?t=detail&id=23498&ct=3&is={}&rid={}".format(li["issueId"],li["resourceId"])
        except:
            pass


        allData.append(tempData)

    return allData

def getData(keyword):

    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Referer': 'http://zq.bookan.com.cn/?t=search&id=23498&ct=1,2,3&rt=0&ft=1&kw=%E5%90%BE',
        'Origin': 'http://zq.bookan.com.cn',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
    }

    params = (
        ('op', 'Search.main'),
        ('resourceTypes', '1,2,3,6'),
        ('keyword', keyword),
        ('instanceId', '23498'),
        ('pageNum', '0'),
        ('byCharacter', '0'),
    )

    response = requests.get('http://user.bookan.com.cn/index.php', headers=headers, params=params)

    allData = formData(response)

    return allData

def index(request):
    data = json.loads(request.POST.get('data', '1'))

    allData = getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")